package com.changgou.seckill.time;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import entity.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 定时将秒杀商品放入redis
 */
@Component
public class SeckillGoodsPushTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    /****
     * 每5秒执行一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void loadGoodsPushRedis(){
        /**
         * 执行步骤
         *  1.查询活动没结束的所有秒杀商品
         * 	1)计算秒杀时间段
         * 	2)状态必须为审核通过 status=1
         * 	3)商品库存个数>0
         * 	4)活动没有结束  endTime>=now()
         * 	5)在Redis中没有该商品的缓存
         * 	6)执行查询获取对应的结果集
         * 2.将活动没有结束的秒杀商品入库
         */

        // 获取时间段
        List<Date> dateMenus = DateUtil.getDateMenus();

        //循环时间段
        for (Date dateMenu : dateMenus) {
            //创建存入redis的namespace
            String namespace = DateUtil.date2Str(dateMenu);
            //查询商品，创建查询商品的Example
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            //添加查询条件
            //审核状态通过
            criteria.andEqualTo("status","1");
            //商品库存大于0
            criteria.andGreaterThan("stockCount",0);
            //活动时间没有结束
            criteria.andGreaterThanOrEqualTo("startTime",dateMenu);
            criteria.andLessThan("endTime",DateUtil.addDateHour(dateMenu,2));
            //所有没有入库的商品的id
            Set keys = redisTemplate.boundHashOps("Seckill_" + namespace).keys();
            if (keys != null && keys.size()>0){
                //使得已入库的商品id不查询
                criteria.andNotIn("id",keys);
            }
            //执行查询
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            //将查询到的商品添加到redis
            for (SeckillGoods seckillGood : seckillGoods) {
                //商品数据队列存储,防止高并发超卖
                Long[] ids = pushIds(seckillGood.getStockCount(), seckillGood.getId());
                redisTemplate.boundListOps("SeckillGoodsCountList_"+seckillGood.getId()).leftPushAll(ids);
                //自增计数器
                redisTemplate.boundHashOps("SeckillGoodsCount").increment(seckillGood.getId(),seckillGood.getStockCount());
                //添加redis
                redisTemplate.boundHashOps("Seckill_" + namespace).put(seckillGood.getId(),seckillGood);
            }
        }

    }

    public Long[] pushIds(Integer count,Long id){
        Long[] ids = new Long[count];
        for (int i = 0; i < ids.length; i++) {
            ids[i] = id;
        }
        return ids;
    }

}
